import cv2
import time
from threading import Thread
from flask import Flask
import logging
import ffmpegcv
from npu_inference import inference

population = 0
stop_monitor = False
app = Flask("ScenicSpotPopulationDetector")
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)


def start_server_thread(port=8888):
    thread_flask = Thread(target=start_flask, args=(port,))
    thread_flask.daemon = True
    thread_flask.start()


def detect(video_path, detection_listener, interval, frame_interval):
    global population
    global stop_monitor

    capture = ffmpegcv.VideoCapture(video_path)

    stop_monitor = False

    now_frame = 0

    while not stop_monitor:
        ret, frame = capture.read()
        if not ret:
            break

        now_frame += 1
        if now_frame % frame_interval != 0:
            continue

        if frame.shape != (640, 640, 3):
            raise Exception("Invalid vide size, only videos with 640x640 are supported.")

        result_number, image = inference.core(frame)
        population = result_number

        detection_listener(image, result_number)

        time.sleep(interval)

    capture.release()


def start_detect_thread(video_path, detection_listener, interval, frame_interval):
    Thread(target=detect, args=(video_path, detection_listener, interval, frame_interval)).start()


@app.route('/population', methods=['GET'])
def get_data():
    return str(population)


def start_flask(port):
    app.run(port=port)


def stop_monitoring():
    global stop_monitor
    stop_monitor = True
